interface ScanPageData {
  type: string;
  cameraAuthorized: boolean;
  scanning: boolean;
}

interface ScanEvent {
  detail: {
    result: string;
    scanType?: string;
    charSet?: string;
    path?: string;
    rawData?: string;
  }
}

type ScanPage = WechatMiniprogram.Page.Instance<
  ScanPageData,
  {
    checkCameraAuth(): Promise<void>;
    handleScanCode(e: ScanEvent): void;
    handleScanError(e: any): void;
    handleManualInput(): void;
    handleCancel(): void;
    handleScanResult(result: string): void;
    formatDate(date: Date): string;
  }
>;

Page({
  data: {
    type: '', // 'inbound' 或 'outbound'
    cameraAuthorized: false,
    scanning: true, // 是否正在扫描
  },

  onLoad(options: Record<'type', string> = { type: '' }) {
    console.log('扫码页面加载，参数：', options);
    this.setData({
      type: options.type || '',
      scanning: true
    });
    this.checkCameraAuth();
  },

  // 格式化日期为 YYYY-MM-DD
  formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 检查相机权限
  async checkCameraAuth() {
    try {
      const { authSetting } = await wx.getSetting();
      if (authSetting['scope.camera']) {
        this.setData({ cameraAuthorized: true });
      } else {
        await wx.authorize({ scope: 'scope.camera' });
        this.setData({ cameraAuthorized: true });
      }
    } catch (error) {
      console.error('相机授权失败：', error);
      this.setData({ cameraAuthorized: false });
      wx.showModal({
        title: '提示',
        content: '需要相机权限才能进行扫码，请在设置中开启相机权限',
        confirmText: '去设置',
        success: (res) => {
          if (res.confirm) {
            wx.openSetting();
          }
        }
      });
    }
  },

  // 扫码成功回调
  handleScanCode(e: ScanEvent) {
    if (!this.data.scanning) return; // 如果不是扫描状态，忽略扫码结果
    
    console.log('扫码结果：', e.detail);
    const result = e.detail.result;
    if (result) {
      this.setData({ scanning: false }); // 停止扫描
      const currentDate = this.formatDate(new Date());
      const operationType = this.data.type === 'inbound' ? '入库' : '出库';
      
      wx.showModal({
        title: '确认信息',
        content: `设备号：${result}\n日期：${currentDate}\n操作：${operationType}`,
        confirmText: '确认',
        cancelText: '重新扫描',
        success: (res) => {
          if (res.confirm) {
            this.handleScanResult(result);
          } else {
            // 重新开始扫描
            this.setData({ scanning: true });
          }
        }
      });
    }
  },

  // 扫码错误回调
  handleScanError(e: any) {
    console.error('扫码错误：', e);
    wx.showToast({
      title: '扫码失败',
      icon: 'error'
    });
  },

  // 处理手动输入
  handleManualInput() {
    wx.showModal({
      title: '手动输入',
      editable: true,
      placeholderText: '请输入设备号',
      success: (res) => {
        if (res.confirm && res.content) {
          const currentDate = this.formatDate(new Date());
          const operationType = this.data.type === 'inbound' ? '入库' : '出库';
          
          wx.showModal({
            title: '确认信息',
            content: `设备号：${res.content}\n 日期：${currentDate}\n操作：${operationType}`,
            confirmText: '确认',
            cancelText: '重新输入',
            success: (confirmRes) => {
              if (confirmRes.confirm) {
                this.handleScanResult(res.content);
              }
            }
          });
        }
      }
    });
  },

  // 处理取消操作
  handleCancel() {
    wx.navigateBack();
  },

  // 处理扫描结果
  handleScanResult(result: string) {
    console.log('处理扫描结果：', result);
    console.log('操作类型：', this.data.type);
    
    const currentDate = this.formatDate(new Date());
    
    // 将结果存储到本地
    const historyList = wx.getStorageSync('scanHistory') || [];
    historyList.unshift({
      code: result,
      type: this.data.type,
      date: currentDate
    });
    wx.setStorageSync('scanHistory', historyList);

    // 显示成功提示
    wx.showToast({
      title: '操作成功',
      icon: 'success',
      duration: 1500,
      success: () => {
        setTimeout(() => {
          // 重置扫描状态，准备下一次扫描
          this.setData({ scanning: true });
        }, 1500);
      }
    });
  }
} as ScanPage); 